#促销商品分组
class ProductGroup
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Attributes::Dynamic


  field :title, type: String
  field :group_type, type: Integer, default: 0 #混合分组（既有促销又有非促销）

  field :start_time, type: DateTime #促销商品开始时间
  field :end_time, type: DateTime #促销商品截止时间

  field :status, type: Integer, default: 0
  field :products,type:Array ,default: []

  has_many :off_promotion_subject_products
  belongs_to :userinfo
  has_one :home_page_subject_field
  has_one :off_promotion_subject
  attr_readonly *fields.keys

  validates_presence_of :title, :start_time, :end_time
  validates_length_of :title, :in => 1..10, :message => "长度在1到10之间"
  validate :before_create_time_validation

  def before_create_time_validation


    errors.add(:start_time, '开始时间应大于结束时间！') if self.start_time.present? && self.end_time.present? && self.start_time >= self.end_time



  end
  def created_at_str
    created_at.strftime("%Y-%m-%d %H:%M:%S")
  end


  def start_time_str
    start_time.strftime("%Y-%m-%d %H:%M:%S")
  end


  def end_time_str
    end_time.strftime("%Y-%m-%d %H:%M:%S")
  end

  def product_count
    self.off_promotion_subject_products.count
  end

  def status_str
    if status==1
      '已启用'
    elsif status==-1
      '已关闭'
    else
      '待启用'
    end
  end


  #获取商品列表
  #product_group_id 分组ID
  #page 页码
  #sort_type 0:综合1:销量升序,2:价格升序，3:价格降序
  def self.get_product_list(product_group_id, sort_type)
    product_array=[]
    OffPromotionSubjectProduct.where(:product_group_id => product_group_id).order_by(:sequencing => :desc).each do |off_promotion_subject_product|


      product = Product.shop_id(off_promotion_subject_product.userinfo_id).find(off_promotion_subject_product.product_id)
      product['sequencing'] = off_promotion_subject_product.sequencing
      product_array << product

    end

    case sort_type
      when 1
        product_array.sort_by { |product| product.sale_count }.reverse
      when 2
        product_array.sort_by { |product| product.current_price }
      when 3
        product_array.sort_by { |product| product.current_price }.reverse
      else
        product_array.sort_by { |product| product.sequencing }.reverse
    end
  end

  def destroy_and_destroy_product_and_update_price


    begin
      #还原商品活动价格
      self.off_promotion_subject_products.where(:is_promotion => 1).each do |promotion|
        #更新商品活动价格
        product = Product.shop_id(promotion['userinfo_id']).find(promotion['product_id'])
        update_params = {}
        update_params['$set'] = {'off_promotion_subject_product_id' => nil, 'panic_price' => 0, 'current_price' => product.price}


        if product.tags_array.include? '促销'

          update_params['$pull'] = {'tags_array' => "促销"}
          update_params['$inc'] = {'tags_array_size' => -1}
        end

        Product.shop_id(promotion['userinfo_id']).where({'_id' => product.id}).update(update_params)

        #更新活动标识
        promotion.update({:status => -1})
      end
      self.off_promotion_subject_products.destroy
      self.destroy

      true
    rescue
      false
    end
  end



  def before_start_validation

    if self.off_promotion_subject_products.count<2
      {:flag => false, :msg => "一个商品分组最少需要两个商品！"}
    elsif self.off_promotion_subject_products.count%2==1
      {:flag => false, :msg => "商品总数必须为偶数"}
    else
      {:flag => true, :msg => "验证通过！"}
    end
  end


  def off_promotion_start

    if self.off_promotion_subject_products.count<2
      {:flag => false, :msg => "一个商品分组最少需要两个商品！"}
    elsif self.off_promotion_subject_products.count%2==1
      {:flag => false, :msg => "商品总数必须为偶数"}
    else
      {:flag => true, :msg => "验证通过！"}
    end
  end
  def off_promotion_close

    begin
      self.off_promotion_subject_products.where(:is_promotion => 1).each do |promotion|
        #更新商品活动价格
        product = Product.shop_id(promotion['userinfo_id']).find(promotion['product_id'])
        update_params = {}
        update_params['$set'] = {'off_promotion_subject_product_id' => nil, 'panic_price' => 0, 'current_price' => product.price}


        if product.tags_array.include? '促销'

          update_params['$pull'] = {'tags_array' => "促销"}
          update_params['$inc'] = {'tags_array_size' => -1}
        end


        Product.shop_id(promotion['userinfo_id']).where({'_id' => product.id}).update(update_params)

        #更新活动标识
        promotion.update({:status => -1})
      end
      {:flag => true, :msg => "关闭成功！"}
    rescue
      {:flag => false, :msg => "关闭失败！"}
    end
  end


end
